<template>
  <div class="detail-container">
    <!-- 顶部统计区域 -->
    <div class="header-section">
      <!-- 标题：鲨鱼记账 -->
      <div class="app-title">
        <van-icon name="bookmark-o" class="title-icon" />
        <span class="title-text">鲨鱼记账</span>
      </div>

      <!-- 账本选择器 -->
      <div class="account-selector" @click="handleAccountSelectorClick">
        <span class="account-name">{{ currentAccountName }}</span>
        <van-icon name="arrow-down" size="14" />
      </div>

      <!-- 年月选择器 -->
      <div class="date-selector" @click="showDatePicker = true">
        <van-icon name="calendar-o" class="calendar-icon" />
        <span class="year">{{ selectedYear }}年</span>
        <span class="month">{{ selectedMonth }}月</span>
        <van-icon name="arrow-down" class="arrow-icon" />
      </div>

      <!-- 收入支出统计 -->
      <div class="summary">
        <div class="summary-item">
          <div class="stat-header">
            <van-icon name="gold-coin-o" class="stat-icon income-icon" />
            <span class="label">收入</span>
          </div>
          <span class="amount income">¥{{ totalIncome.toFixed(2) }}</span>
        </div>
        <div class="divider"></div>
        <div class="summary-item">
          <div class="stat-header">
            <van-icon name="balance-list-o" class="stat-icon expense-icon" />
            <span class="label">支出</span>
          </div>
          <span class="amount expense">¥{{ totalExpense.toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <!-- 账单列表 -->
    <div class="bill-list">
      <div v-if="groupedBills.length === 0" class="empty-state">
        <van-empty description="暂无账单记录" />
      </div>
      
      <div v-else>
        <div v-for="group in groupedBills" :key="group.date" class="date-group">
          <!-- 日期标题 -->
          <div class="date-header">
            <span class="date-text">{{ group.dateText }}</span>
            <span class="day-summary">
              支出: {{ group.dayExpense.toFixed(2) }}
            </span>
          </div>

          <!-- 当天的账单列表（使用滑动单元格支持删除） -->
          <div class="bill-items">
            <van-swipe-cell 
              v-for="bill in group.bills" 
              :key="bill.id"
            >
              <div 
                class="bill-item"
                @click="handleBillEdit(bill)"
              >
                <div class="bill-icon">
                  <van-icon :name="getCategoryIcon(bill.category)" />
                </div>
                <div class="bill-info">
                  <div class="bill-category">{{ bill.categoryName }}</div>
                  <div class="bill-remark">{{ bill.remark || '无备注' }}</div>
                </div>
                <div class="bill-amount" :class="bill.type === 1 ? 'expense' : 'income'">
                  {{ bill.type === 1 ? '-' : '+' }}{{ bill.amount.toFixed(2) }}
                </div>
              </div>
              <template #right>
                <van-button 
                  square 
                  text="删除" 
                  type="danger" 
                  class="delete-button"
                  @click="handleBillDelete(bill)"
                />
              </template>
            </van-swipe-cell>
          </div>
        </div>
      </div>
    </div>

    <!-- 日期选择器弹出层 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        v-model="currentDate"
        type="year-month"
        title="选择年月"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>

    <!-- 编辑账单弹窗 -->
    <van-popup 
      v-model:show="showEditPopup" 
      position="bottom" 
      round
      :style="{ padding: '20px' }"
    >
      <div class="edit-popup">
        <h3 class="edit-title">编辑账单</h3>
        <van-form @submit="handleEditSubmit">
          <van-field
            v-model="editForm.amount"
            name="amount"
            label="金额"
            type="digit"
            placeholder="请输入金额"
            :rules="[{ required: true, message: '请输入金额' }]"
          />
          <van-field
            v-model="editForm.remark"
            name="remark"
            label="备注"
            placeholder="请输入备注（选填）"
            maxlength="100"
          />
          <van-field
            v-model="editForm.dateStr"
            name="date"
            label="日期"
            placeholder="选择日期"
            readonly
            @click="showEditDatePicker = true"
          />
          <div class="edit-buttons">
            <van-button block @click="showEditPopup = false">取消</van-button>
            <van-button block type="primary" native-type="submit">保存</van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <!-- 编辑日期选择器 -->
    <van-popup v-model:show="showEditDatePicker" position="bottom">
      <van-date-picker
        v-model="editDateValue"
        title="选择日期"
        :min-date="new Date(2020, 0, 1)"
        :max-date="new Date(2030, 11, 31)"
        @confirm="onEditDateConfirm"
        @cancel="showEditDatePicker = false"
      />
    </van-popup>

    <!-- 账本选择器弹窗 -->
    <van-popup v-model:show="showAccountPicker" position="bottom" round>
      <van-picker
        :columns="accountColumns"
        @confirm="onAccountConfirm"
        @cancel="showAccountPicker = false"
        :default-index="currentAccountIndex"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showSuccessToast, showConfirmDialog } from 'vant'
import { getBillDetail, updateTallyRecord, deleteTallyRecord } from '@/api/index'
import { useAccountStore } from '@/stores/account'

const router = useRouter()
const route = useRoute()
const accountStore = useAccountStore()

// 日期相关
const selectedYear = ref(new Date().getFullYear())
const selectedMonth = ref(new Date().getMonth() + 1)
const showDatePicker = ref(false)
const showAccountPicker = ref(false)
// van-date-picker 的 v-model 需要数组格式 [year, month]
const currentDate = ref([
  new Date().getFullYear(), 
  new Date().getMonth() + 1
])
const minDate = ref(new Date(2020, 0, 1))
const maxDate = ref(new Date(2030, 11, 31))

// 账本相关
const accountList = computed(() => accountStore.accountList)
const currentAccount = computed(() => accountStore.currentAccount)

// 当前账本名称
const currentAccountName = computed(() => {
  return currentAccount.value ? currentAccount.value.remark : '全部账本'
})

// 账本选择器列数据
const accountColumns = computed(() => {
  const allAccount = { text: '全部账本', value: null }
  const accounts = accountList.value.map(account => ({
    text: account.remark,
    value: account.id
  }))
  return [allAccount, ...accounts]
})

// 当前账本在列表中的索引
const currentAccountIndex = computed(() => {
  if (!currentAccount.value) return 0
  return accountList.value.findIndex(a => a.id === currentAccount.value.id) + 1
})

// 统计数据
const totalIncome = ref(0)
const totalExpense = ref(0)

// 账单数据
const billsList = ref([])

// 编辑相关
const showEditPopup = ref(false)
const showEditDatePicker = ref(false)
const editingBill = ref(null)
const editForm = ref({
  amount: '',
  remark: '',
  dateStr: ''
})
const editDateValue = ref([
  new Date().getFullYear(),
  new Date().getMonth() + 1,
  new Date().getDate()
])

// 按日期分组的账单
const groupedBills = computed(() => {
  const groups = {}
  
  billsList.value.forEach(bill => {
    const date = bill.date
    if (!groups[date]) {
      groups[date] = {
        date,
        dateText: formatDate(date),
        bills: [],
        dayExpense: 0,
        dayIncome: 0
      }
    }
    
    groups[date].bills.push(bill)
    if (bill.type === 1) {
      groups[date].dayExpense += bill.amount
    } else {
      groups[date].dayIncome += bill.amount
    }
  })
  
  // 转换为数组并按日期降序排序
  return Object.values(groups).sort((a, b) => new Date(b.date) - new Date(a.date))
})

// 格式化日期显示
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekday = weekdays[date.getDay()]
  
  return `${month}月${day}日 ${weekday}`
}

// 获取分类图标（需要与后端分类映射一致）
const getCategoryIcon = (categoryId) => {
  const iconMap = {
    // 支出类别
    1: 'hot-o',           // 餐饮
    2: 'shopping-cart-o', // 购物
    3: 'bag-o',           // 日用
    4: 'logistics',       // 交通
    5: 'flower-o',        // 蔬菜
    6: 'smile-o',         // 水果
    7: 'setting-o',       // 设置
    // 收入类别（如果需要）
    // 也可以根据type来区分不同的图标
  }
  return iconMap[categoryId] || 'balance-o'
}

// 日期选择确认
const onDateConfirm = (selectedValue) => {
  console.log('日期选择器返回值:', selectedValue, '类型:', typeof selectedValue)
  
  // van-date-picker 返回的是对象 { selectedValues: [year, month] }
  // 需要从 currentDate.value 中获取选中的值
  const year = currentDate.value[0]
  const month = currentDate.value[1]
  
  console.log('解析后的年月:', year, month)
  
  // 验证数据有效性
  if (!year || !month || isNaN(year) || isNaN(month)) {
    console.error('日期数据无效:', { year, month })
    showToast('请选择有效的日期')
    return
  }
  
  // 更新选中的年月
  selectedYear.value = Number(year)
  selectedMonth.value = Number(month)
  
  showDatePicker.value = false
  
  console.log(`选择的日期: ${selectedYear.value}年${selectedMonth.value}月`)
  
  // 根据选择的年月重新获取数据
  fetchBillData()
}

// 点击账本选择器
const handleAccountSelectorClick = () => {
  console.log('点击账本选择器，账本数量:', accountList.value.length)
  
  if (accountList.value.length === 0) {
    showConfirmDialog({
      title: '提示',
      message: '你还没有账本，是否跳转到账本页添加账本？',
      confirmButtonText: '去添加',
      cancelButtonText: '取消',
    })
      .then(() => {
        // 点击确认，跳转到账本管理页面
        router.push('/ledger')
      })
      .catch(() => {
        // 点击取消，不做任何操作
      })
    return
  }
  
  showAccountPicker.value = true
}

// 确认选择账本
const onAccountConfirm = ({ selectedOptions }) => {
  const selected = selectedOptions[0]
  const account = accountList.value.find(a => a.id === selected.value)
  
  console.log('选择账本:', selected, account)
  
  if (selected.value === null) {
    // 选择了"全部账本"
    accountStore.setCurrentAccount(null)
    showToast('已切换到全部账本')
  } else if (account) {
    accountStore.setCurrentAccount(account)
    showToast(`已切换到：${account.remark}`)
  }
  
  showAccountPicker.value = false
  
  // 重新加载数据
  fetchBillData()
}

// 获取账单数据
const fetchBillData = async () => {
  try {
    console.log(`获取 ${selectedYear.value}年${selectedMonth.value}月 的账单数据`)
    
    const params = {
      year: selectedYear.value,
      month: selectedMonth.value
    }
    
    // 如果选择了特定账本，添加账本ID参数
    if (currentAccount.value) {
      params.accountId = currentAccount.value.id
      console.log('当前账本ID:', params.accountId)
    }
    
    const res = await getBillDetail(params)
    
    console.log('账单明细返回数据:', res)
    
    if (res) {
      // 更新统计数据
      totalIncome.value = res.totalIncome || 0
      totalExpense.value = res.totalExpense || 0
      
      // 更新账单列表
      billsList.value = res.bills || []
      
      console.log('账单数据更新完成:', {
        income: totalIncome.value,
        expense: totalExpense.value,
        count: billsList.value.length
      })
    } else {
      // 无数据时清空
      totalIncome.value = 0
      totalExpense.value = 0
      billsList.value = []
    }
  } catch (error) {
    console.error('获取账单数据失败:', error)
    showToast(error.message || '获取数据失败')
    // 出错时清空数据
    totalIncome.value = 0
    totalExpense.value = 0
    billsList.value = []
  }
}

// 编辑账单
const handleBillEdit = (bill) => {
  console.log('编辑账单:', bill)
  editingBill.value = bill
  
  // 填充表单
  editForm.value.amount = String(bill.amount)
  editForm.value.remark = bill.remark || ''
  editForm.value.dateStr = bill.date
  
  // 解析日期
  const dateObj = new Date(bill.date)
  editDateValue.value = [
    dateObj.getFullYear(),
    dateObj.getMonth() + 1,
    dateObj.getDate()
  ]
  
  showEditPopup.value = true
}

// 编辑日期确认
const onEditDateConfirm = () => {
  const [year, month, day] = editDateValue.value
  editForm.value.dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
  showEditDatePicker.value = false
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    const data = {
      type: editingBill.value.type,
      flag: editingBill.value.category,
      price: Number(editForm.value.amount),
      remark: editForm.value.remark,
      createTime: new Date(editForm.value.dateStr).getTime()
    }
    
    console.log('更新账单数据:', data)
    
    await updateTallyRecord(editingBill.value.id, data)
    showSuccessToast('修改成功')
    showEditPopup.value = false
    
    // 重新加载数据
    fetchBillData()
  } catch (error) {
    console.error('修改账单失败:', error)
    showToast(error.message || '修改失败')
  }
}

// 删除账单
const handleBillDelete = (bill) => {
  showConfirmDialog({
    title: '删除确认',
    message: `确定要删除这条账单吗？`,
    confirmButtonText: '删除',
    confirmButtonColor: '#ee0a24',
  })
    .then(async () => {
      try {
        await deleteTallyRecord(bill.id)
        showSuccessToast('删除成功')
        
        // 重新加载数据
        fetchBillData()
      } catch (error) {
        console.error('删除账单失败:', error)
        showToast(error.message || '删除失败')
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 初始化账本数据的函数
const initAccountData = async () => {
  console.log('开始初始化账本数据...')
  
  // 恢复上次选择的账本
  accountStore.restoreCurrentAccount()
  console.log('恢复的账本:', currentAccount.value)
  
  // 刷新账本列表（每次都重新加载以获取最新数据）
  console.log('刷新账本列表...')
  await accountStore.refreshAccountList()
  
  console.log('账本列表:', accountList.value)
  console.log('当前账本:', currentAccount.value)
  
  fetchBillData()
}

// 监听路由变化，从账本页返回时刷新
watch(() => route.path, (newPath, oldPath) => {
  if (newPath === '/detail' && oldPath === '/ledger') {
    console.log('从账本页返回，刷新账本数据')
    initAccountData()
  }
})

// 页面加载时获取数据
onMounted(async () => {
  console.log('Detail页面 onMounted')
  await initAccountData()
})
</script>

<style lang='scss' scoped>
.detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 70px; /* 为底部导航留出空间 */
}

/* 顶部统计区域 */
.header-section {
  background: linear-gradient(135deg, #FFD844, #FFC107);
  padding: 16px;
  border-radius: 0 0 24px 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.header-section::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -20%;
  width: 200px;
  height: 200px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.2) 0%, transparent 70%);
  border-radius: 50%;
}

/* 标题：鲨鱼记账 */
.app-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
  gap: 8px;
  position: relative;
  z-index: 1;

  .title-icon {
    font-size: 24px;
    color: #333;
  }

  .title-text {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    letter-spacing: 2px;
  }
}

/* 账本选择器 */
.account-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px 16px;
  margin-bottom: 12px;
  cursor: pointer;
  user-select: none;
  position: relative;
  z-index: 1;
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.98);
  }

  .account-name {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.7);
    margin-right: 4px;
    font-weight: 500;
  }

  :deep(.van-icon) {
    color: rgba(0, 0, 0, 0.6);
  }
}

/* 年月选择器 */
.date-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 20px;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;

  &:active {
    transform: scale(0.98);
    background: rgba(255, 255, 255, 0.7);
  }

  .calendar-icon {
    font-size: 18px;
    color: #333;
    margin-right: 8px;
  }

  .year {
    font-size: 15px;
    color: rgba(0, 0, 0, 0.7);
    margin-right: 4px;
  }

  .month {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin-right: 6px;
  }

  .arrow-icon {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.6);
  }
}

/* 收入支出统计 */
.summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.6);
  padding: 16px 20px;
  border-radius: 16px;
  position: relative;
  z-index: 1;

  .summary-item {
    flex: 1;
    text-align: center;

    .stat-header {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
      margin-bottom: 8px;

      .stat-icon {
        font-size: 16px;

        &.income-icon {
          color: #52c41a;
        }

        &.expense-icon {
          color: #ff6b6b;
        }
      }

      .label {
        font-size: 13px;
        color: rgba(0, 0, 0, 0.6);
        font-weight: 500;
      }
    }

    .amount {
      display: block;
      font-size: 22px;
      font-weight: bold;

      &.income {
        color: #52c41a;
      }

      &.expense {
        color: #ff6b6b;
      }
    }
  }

  .divider {
    width: 1px;
    height: 50px;
    background: rgba(0, 0, 0, 0.1);
  }
}

/* 账单列表 */
.bill-list {
  padding: 16px;
}

.empty-state {
  margin-top: 100px;
}

/* 日期分组 */
.date-group {
  margin-bottom: 16px;
}

.date-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
  color: #666;

  .date-text {
    font-weight: 500;
  }

  .day-summary {
    font-size: 12px;
    color: #999;
  }
}

/* 账单项 */
.bill-items {
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;

  :deep(.van-swipe-cell) {
    border-bottom: 1px solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }
  }

  .delete-button {
    height: 100%;
  }
}

.bill-item {
  display: flex;
  align-items: center;
  padding: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  background-color: #fff;

  &:active {
    background-color: #f9f9f9;
  }

  .bill-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #FFF3CD;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;

    :deep(.van-icon) {
      font-size: 22px;
      color: #FFB300;
    }
  }

  .bill-info {
    flex: 1;

    .bill-category {
      font-size: 15px;
      color: #333;
      margin-bottom: 4px;
    }

    .bill-remark {
      font-size: 13px;
      color: #999;
    }
  }

  .bill-amount {
    font-size: 18px;
    font-weight: 600;

    &.expense {
      color: #333;
    }

    &.income {
      color: #52C41A;
    }
  }
}

/* 编辑弹窗 */
.edit-popup {
  padding-bottom: 20px;

  .edit-title {
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0 0 20px 0;
    color: #333;
  }

  .edit-buttons {
    display: flex;
    gap: 12px;
    margin-top: 16px;

    .van-button {
      flex: 1;
    }
  }
}
</style>